package com.cloud.util;

import java.util.concurrent.*;

public class SpiderThreadPool {

    private static final int N_CPU = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = N_CPU * 2;
    private static final int MAX_POOL_SIZE = CORE_POOL_SIZE * 2;
    private static final int QUEUE_CAPACITY = 10000;
    private static final Long KEEP_ALIVE_TIME = 1L;
    private static final int AWAIT_TIME_INTERVAL = 500;


    //通过ThreadPoolExecutor构造函数自定义参数创建
    private volatile static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(QUEUE_CAPACITY),
            new ThreadPoolExecutor.CallerRunsPolicy());


    private SpiderThreadPool() {

    }

    public static ThreadPoolExecutor getInstance() {
        return executor;
    }

    public static <T> Future<T> submit(Callable<T> callable) {
        return executor.submit(callable);
    }

    public static void submit(Runnable runnable) {
        executor.submit(runnable);
    }

    public static void shutdown() {
        executor.shutdown();
        try {
            boolean flag = executor.awaitTermination(AWAIT_TIME_INTERVAL, TimeUnit.MILLISECONDS);
            while (!flag) {
                flag = executor.awaitTermination(AWAIT_TIME_INTERVAL, TimeUnit.MILLISECONDS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
